package advanced.thread;

/**
 * ThreadLocal 会保证每个线程有自身的存储
 * 本地, 局部区域
 * 更改不会影响其他线程
 */
public class L_ThreadLocal {

    //    private static ThreadLocal<Integer> threadLocal=new ThreadLocal<>();
    //更改threadLocal的值 方法1
/*    private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>() {

        @Override
        protected Integer initialValue() {
            return 200;
        }
    };*/
    //更改threadlocal的初始值 方法2
    private static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 200);

    public static void main(String[] args) throws InterruptedException {
        //获取值
        System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());
        //设置值
        threadLocal.set(99);
        System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());
        new Thread(new MyRun()).start();
        Thread.sleep(5000);
        //main线程里的threadlocal值 不受 myrun线程里的修改影响
        System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());

    }

    public static class MyRun implements Runnable {

        @Override
        public void run() {
            //threaLocal  若是InheritableThreadLocal 的对象 它会继承上下文的数据,作为初始值, 但是它的对数据的更改,仅在本线程的作用域内有效
            threadLocal.set((int) (Math.random() * 99));
            System.out.println(Thread.currentThread().getName() + "-->" + threadLocal.get());
        }
    }
}

